class RealIPMiddleware:
    '''
    Do not use this middleware in non-proxy setups for security reasons.

    Example nginx config:

    location / {
          # needed to forward user's IP address to rails
          proxy_set_header  X-Real-IP  $remote_addr;

          # needed for HTTPS
          proxy_set_header X-FORWARDED-PROTO https;

          proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $http_host;
          proxy_redirect false;
          proxy_max_temp_file_size 0;

          proxy_pass http://upstream;
        }
    '''
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        # Squid uses X-Forwarded-For, others use X-Real-IP or X-Real-Ip.
        #   X-Forwarded-For: environ.get('HTTP_X_FORWARDED_FOR', '').split(',')[0]
        remote_ip = environ.get('HTTP_X_REAL_IP')
        if remote_ip:
            environ['REMOTE_ADDR'] = remote_ip

        forwarded_proto = environ.get('HTTP_X_FORWARDED_PROTO')
        if forwarded_proto:
            environ['wsgi.url_scheme'] = forwarded_proto

        return self.app(environ, start_response)


class HostVarCheckMiddleware:
    allowed_hosts=('localhost', '127.0.0.1')

    def __init__(self, app, allowed_hosts=None):
        self.app = app
        self.allowed_hosts = allowed_hosts or self.allowed_hosts

    def __call__(self, environ, start_response):
        host = environ.get('HTTP_HOST')
        if host and host not in self.allowed_hosts:
            start_response(b'400 Bad response', [])
            return [b'Bad response']
        return self.app(environ, start_response)

